package common

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go/v4"
)

type MyCustomClaims struct {
	Id       int
	Username string
	jwt.StandardClaims
}

var (
	key, _ = beego.AppConfig.String("mySigningKey")
)

func CreateToken(claims *MyCustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString([]byte(key))
	return ss, err
}

func ParseToken(tokens string) (int, int64) {
	token, err := jwt.ParseWithClaims(tokens, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(key), nil
	})

	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		fmt.Printf("%v %v", claims.Id, claims.StandardClaims.ExpiresAt.Unix())
		return claims.Id, claims.StandardClaims.ExpiresAt.Unix()
	} else {
		fmt.Println(err)
		return 0, 0
	}
}
